package com.fenghongzhang.day009;

import androidx.appcompat.app.AppCompatActivity;

import android.content.ContentValues;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.os.Bundle;
import android.view.View;
import android.widget.Toast;

public class MainActivity extends AppCompatActivity {

    private SQLiteDatabase readableDatabase;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        //相当于建立链接
        MySqlHelper mySqlHelper = new MySqlHelper(this, "user.db", null, 2);
        //打开一个数据库
        readableDatabase = mySqlHelper.getReadableDatabase();//打开

    }

    public void create(View view) {

    }

    public void createTable(View view) {
        //创建表
        String sql = "create table student(id integer primary key autoincrement,name varchar(20))";
        readableDatabase.execSQL(sql);
    }

    public void insert(View view) {
        //插入数据 ? 占位符
//        String sql = "insert into student values(null,?)";
//        readableDatabase.execSQL(sql,new Object[]{"猴子"});

        ContentValues contentValues = new ContentValues();
        contentValues.put("name","哈哈");
        readableDatabase.insert("student",null,contentValues);
    }

    public void query(View view) {
        //查询数据
//        String sql = "select * from student ";
//        Cursor cursor = readableDatabase.rawQuery(sql,null);
//        if(cursor != null){
//            while(cursor.moveToNext()){
//                String name = cursor.getString(cursor.getColumnIndex("name"));
//                Toast.makeText(this, name, Toast.LENGTH_SHORT).show();
//            }
//            cursor.close();
//        }

        Cursor cursor = readableDatabase.query("student", null, null, null, null, null, null);
        if(cursor != null){
            while(cursor.moveToNext()){
                String name = cursor.getString(cursor.getColumnIndex("name"));
                Toast.makeText(this, name, Toast.LENGTH_SHORT).show();
            }
            cursor.close();
        }
    }

    public void del(View view) {
//        String sql = "delete from student where id = ?";
//        readableDatabase.execSQL(sql,new Object[]{100});
        readableDatabase.delete("student","id = ?",new String[]{"4"});
    }

    public void update(View view) {
//        String sql = "update student set name=? where id = ?";
//        readableDatabase.execSQL(sql,new Object[]{"李白",3});
        ContentValues contentValues = new ContentValues();
        contentValues.put("name","呵呵");
        //"update student set name=? ";
        /**
         * 1,表明
         * 2,要修改的字段值
         * 3,where 条件
         * 4,给条件赋值
         */
        readableDatabase.update("student",contentValues,"id = ?",new String[]{"4"});
    }
}
